package com.scau.bookstore.api.util;

import com.scau.bookstore.api.exception.AuthException;
import com.scau.bookstore.api.exception.TokenException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * todo: jwt工具，分布式环境会生效吗？
 */
public class JwtUtil {

    // 过期时间60分钟
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    private static Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    /**
     * 创建token
     *
     * @param id
     * @param username
     * @return
     */
    public static String createToken(Long id, String username) {
        Date expiredDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //可以将基本不重要的对象信息放到claims中
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("username", username);
        return Jwts.builder()
                .setClaims(claims)
                .setId(String.valueOf(id))  // todo: 加密
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(expiredDate)
                .signWith(key)
                .compact();
    }

    /**
     * 获取token存储的内容
     *
     * @param token
     * @return
     */
    private static Claims parseToken(String token) {
        // todo: 异常处理
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            throw new TokenException("无效的token");
        }

        return claims;
    }

    public static Long getIdByToken(String token) {
        Map<String, Object> map = parseToken(token);
        Integer id = (Integer) map.get("id");   // todo: 异常处理
        return Long.valueOf(id);
    }

    public static String getUsernameByToken(String token) {
        Map<String, Object> map = parseToken(token);
        String username = (String) map.get("username"); // todo: 异常处理
        return username;
    }
}
